package com.hqq.persistence_tier.dao;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Stream;

/**
 * InMemoryCustomerDao
 * 实现了{@link CustomerDao} 将数据保存在JVM中 当应用程序退出时清除数据
 * 适合用于测试的临时数据库
 * Created by heqianqian on 2017/8/9.
 */
public class InMemoryCustomerDao implements CustomerDao {

    private Map<Integer, Customer> idToCustomer = new HashMap<>();

    /**
     * 及早求值
     */
    @Override
    public Stream<Customer> getAll() throws Exception {
        return idToCustomer.values().stream();
    }

    @Override
    public Optional<Customer> getById(int id) throws Exception {
        if (idToCustomer.get(id) != null) {
            return Optional.of(idToCustomer.get(id));
        } else {
            return Optional.empty();
        }
    }

    @Override
    public boolean add(Customer customer) throws Exception {
        if (getById(customer.getId()).isPresent()) {
            return false;
        }
        idToCustomer.put(customer.getId(), customer);
        return true;
    }

    @Override
    public boolean update(Customer customer) throws Exception {
        return idToCustomer.replace(customer.getId(), customer) != null;
    }

    @Override
    public boolean delete(Customer customer) throws Exception {
        return idToCustomer.remove(customer.getId()) != null;
    }
}
